import { h, defineComponent, toRefs, onMounted, onUnmounted } from '@vue/runtime-core';
import enemyPlaneImg from '../../assets/enemy.png'
// import enemyPlaneImg from '../../assets/me.jpg'

export const enemyPlaneInfo = {
  width: 308,
  height: 207,
  life: 3
}

// 敌方飞机
export default defineComponent({
  props: ['x', 'y'],
  setup(props, ctx) {
    // 解构会丢失引用，所以这里需要使用 toRefs
    // toRefs 和 reactive 的区别：
    const { x, y } = toRefs(props)

    useAttack(ctx, x, y);

    return {
      x, y
    }
  },
  render(ctx) {
    return h("Sprite", {
      x: ctx.x,  // 容器的 x
      y: ctx.y,   // 容器的 y
      texture: enemyPlaneImg
    })
  }
})

// 发射子弹
const useAttack = (ctx, x, y) => {
  const attackInterval = 2000;
  let intervalId;

  onMounted(() => {
    intervalId = setInterval(() => {
      ctx.emit("attack", {
        x: x.value + 105,
        y: y.value + 200,
      })
    }, attackInterval)
  })

  onUnmounted(() => {
    clearInterval(intervalId)
  })
}